import React, { useState } from 'react';
import { View, Text, SafeAreaView, Image, TouchableOpacity, Modal, TextInput, Alert } from 'react-native';
import { styles } from './styles';
import CustomQRScanner from '../../../components/CustomQRScanner';
import saoma from '../../../assets/saoma.png';
import { checkTaskApi, logoutApi } from './api';
import ProductionReport from './ProductionReport';
import PersonalCenter from './PersonalCenter';
import WorkOrderDispatch from './WorkOrderDispatch';
import ProcessDispatch from './ProcessDispatch';
import HomeworkGuidance from './HomeworkGuidance';
import ProductionTasks from './ProductionTasks';
import { Toast } from '@ant-design/react-native';

interface ReportWorkProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
}

const ReportWork: React.FC<ReportWorkProps> = ({ onNavigateToLogin, onBackPress }) => {
    const [workOrderModalVisible, setWorkOrderModalVisible] = useState(false);
    const [scanModalVisible, setScanModalVisible] = useState(false);
    const [workOrderNumber, setWorkOrderNumber] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [showProductionReport, setShowProductionReport] = useState(false);
    const [showPersonalCenter, setShowPersonalCenter] = useState(false);
    const [showWorkOrderDispatch, setShowWorkOrderDispatch] = useState(false);
    const [showProcessDispatch, setShowProcessDispatch] = useState(false);
    const [showHomeworkGuidance, setShowHomeworkGuidance] = useState(false);
    const [showProductionTasks, setShowProductionTasks] = useState(false);
    const [apiResponseData, setApiResponseData] = useState<any>(null);

    const cards = [
        {
            id: 1,
            title: '生产报工',
            image: require('../../../assets/terminal/scbg.png'),
        },
        {
            id: 2,
            title: '个人中心',
            image: require('../../../assets/terminal/gwjl.png'),
        },
        {
            id: 3,
            title: '工单派工',
            image: require('../../../assets/terminal/xcgl.png'),
        },
        {
            id: 4,
            title: '工序派工',
            image: require('../../../assets/terminal/gwjl.png'),
        },
        {
            id: 5,
            title: '作业指导',
            image: require('../../../assets/terminal/zyzd.png'),
        },
        {
            id: 6,
            title: '生产任务',
            image: require('../../../assets/terminal/scrw.png'),
        },
    ];

    const handleCardPress = (cardId: number) => {
        console.log('Card pressed:', cardId);
        if (cardId === 1) {
            // 生产报工
            setWorkOrderModalVisible(true);
        } else if (cardId === 2) {
            // 个人中心
            setShowPersonalCenter(true);
        } else if (cardId === 3) {
            // 工单派工
            setShowWorkOrderDispatch(true);
        } else if (cardId === 4) {
            // 工序派工
            setShowProcessDispatch(true);
        } else if (cardId === 5) {
            // 作业指导
            setShowHomeworkGuidance(true);
        } else if (cardId === 6) {
            // 生产任务
            setShowProductionTasks(true);
        }
        // 这里可以添加其他卡片的导航逻辑
    };

    const handleScanPress = () => {
        setWorkOrderModalVisible(false);
        setScanModalVisible(true);
    };

    const handleScanResult = (data: string) => {
        console.log('扫码成功:', data);
        setScanModalVisible(false);
        setWorkOrderNumber(data);
        // 扫码成功后重新打开工单模态框
        setTimeout(() => {
            setWorkOrderModalVisible(true);
        }, 100);
    };

    const handleScanClose = () => {
        console.log('扫码模态框关闭');
        setScanModalVisible(false);
        // 关闭扫码模态框后重新打开工单模态框
        setTimeout(() => {
            setWorkOrderModalVisible(true);
        }, 100);
    };

    const handleConfirm = async () => {
        if (!workOrderNumber.trim()) {
            Toast.fail('请输入工单号');
            return;
        }

        setIsLoading(true);
        try {
            console.log('确认工单号:', workOrderNumber);
            const response = await checkTaskApi(workOrderNumber);

            if (response.code === 200) {
                console.log('API调用成功，准备跳转到生产报工页面');
                setApiResponseData(response);
                setWorkOrderModalVisible(false);
                setWorkOrderNumber('');
                setShowProductionReport(true);
            } else {
                Toast.fail(response.msg || '工单号验证失败');
            }
        } catch (error) {
            console.error('API调用失败:', error);
            Toast.fail('网络请求失败，请重试');
        } finally {
            setIsLoading(false);
        }
    };

    const handleCancel = () => {
        setWorkOrderModalVisible(false);
        setWorkOrderNumber('');
    };

    const handleBackFromProductionReport = () => {
        setShowProductionReport(false);
        setApiResponseData(null);
    };

    const handleBackFromPersonalCenter = () => {
        setShowPersonalCenter(false);
    };

    const handleBackFromWorkOrderDispatch = () => {
        setShowWorkOrderDispatch(false);
    };

    const handleBackFromProcessDispatch = () => {
        setShowProcessDispatch(false);
    };

    const handleBackFromHomeworkGuidance = () => {
        setShowHomeworkGuidance(false);
    };

    const handleBackFromProductionTasks = () => {
        setShowProductionTasks(false);
    };

    // 处理Logo点击事件
    const handleLogoPress = () => {
        Alert.alert(
            '确认退出',
            '确定要退出登录吗？',
            [
                {
                    text: '取消',
                    style: 'cancel',
                },
                {
                    text: '确定',
                    onPress: handleLogout,
                },
            ]
        );
    };

    // 执行退出登录
    const handleLogout = async () => {
        try {
            console.log('用户确认退出，准备调用退出登录接口');
            const response = await logoutApi();

            if (response.code === 200) {
                console.log('退出登录成功，准备跳转到登录页');
                Toast.success(response.msg || '退出登录成功');
                // 调用父组件的登录导航函数
                if (onNavigateToLogin) {
                    onNavigateToLogin();
                }
            } else {
                console.log('退出登录失败:', response.msg);
                Toast.fail(response.msg || '退出登录失败');
            }
        } catch (error) {
            console.error('退出登录接口调用失败:', error);
            Toast.fail('网络请求失败，请重试');
        }
    };

    // 如果显示生产报工页面，则渲染该页面
    if (showProductionReport) {
        return (
            <ProductionReport
                onBackPress={handleBackFromProductionReport}
                apiData={apiResponseData}
            />
        );
    }

    // 如果显示个人中心页面，则渲染该页面
    if (showPersonalCenter) {
        return (
            <PersonalCenter
                onBackPress={handleBackFromPersonalCenter}
            />
        );
    }

    // 如果显示工单派工页面，则渲染该页面
    if (showWorkOrderDispatch) {
        return (
            <WorkOrderDispatch
                onBackPress={handleBackFromWorkOrderDispatch}
            />
        );
    }

    // 如果显示工序派工页面，则渲染该页面
    if (showProcessDispatch) {
        return (
            <ProcessDispatch
                onBackPress={handleBackFromProcessDispatch}
            />
        );
    }

    // 如果显示作业指导页面，则渲染该页面
    if (showHomeworkGuidance) {
        return (
            <HomeworkGuidance
                onBackPress={handleBackFromHomeworkGuidance}
            />
        );
    }

    // 如果显示生产任务页面，则渲染该页面
    if (showProductionTasks) {
        return (
            <ProductionTasks
                onBackPress={handleBackFromProductionTasks}
            />
        );
    }

    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.header}>
                <Image
                    source={require('../../../assets/terminal/home-header.png')}
                    style={styles.headerBackground}
                    resizeMode="cover"
                />
                <View style={styles.headerContent}>
                    <TouchableOpacity
                        style={styles.logo}
                        onPress={handleLogoPress}
                        activeOpacity={0.7}
                    >
                        <Image
                            source={require('../../../assets/terminal/home-logo.png')}
                            style={{ width: '100%', height: '100%' }}
                            resizeMode="contain"
                        />
                    </TouchableOpacity>
                    <Text style={styles.headerText}>MES终端服务系统</Text>
                </View>
            </View>
            <View style={styles.content}>
                <View style={styles.cardsContainer}>
                    {cards.map((card) => (
                        <TouchableOpacity
                            key={card.id}
                            style={styles.card}
                            onPress={() => handleCardPress(card.id)}
                        >
                            <Image
                                source={card.image}
                                style={styles.cardBackground}
                                resizeMode="cover"
                            />
                            <View style={{
                                position: 'absolute',
                                bottom: 20,
                                left: 0,
                                right: 0,
                                alignItems: 'center',
                            }}>
                                <Text style={styles.cardText}>{card.title}</Text>
                            </View>
                        </TouchableOpacity>
                    ))}
                </View>
            </View>

            {/* 生产报工模态框 */}
            <Modal
                visible={workOrderModalVisible}
                transparent={true}
                animationType="fade"
                onRequestClose={handleCancel}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContainer}>
                        <View style={styles.modalHeader}>
                            <Text style={styles.modalTitle}>生产报工</Text>
                            <TouchableOpacity onPress={handleCancel}>
                                <Text style={styles.closeButton}>×</Text>
                            </TouchableOpacity>
                        </View>

                        <View style={styles.inputContainer}>
                            <Text style={styles.inputLabel}>工单号</Text>
                            <View style={styles.inputRow}>
                                <TextInput
                                    style={styles.textInput}
                                    placeholder="请扫描工单号"
                                    value={workOrderNumber}
                                    onChangeText={setWorkOrderNumber}
                                />
                                <TouchableOpacity style={styles.scanButton} onPress={handleScanPress}>
                                    <Image source={saoma} style={styles.scanIcon} />
                                </TouchableOpacity>
                            </View>
                        </View>

                        <View style={styles.modalButtons}>
                            <TouchableOpacity
                                style={styles.cancelModalButton}
                                onPress={handleCancel}
                                disabled={isLoading}
                            >
                                <Text style={styles.cancelModalButtonText}>取消</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[
                                    styles.confirmModalButton,
                                    isLoading && styles.confirmModalButtonDisabled
                                ]}
                                onPress={handleConfirm}
                                disabled={isLoading}
                            >
                                <Text style={styles.confirmModalButtonText}>
                                    {isLoading ? '处理中...' : '确认'}
                                </Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>

            {/* 扫码模态框 */}
            <Modal visible={scanModalVisible} animationType="slide">
                <CustomQRScanner
                    onRead={handleScanResult}
                    onClose={handleScanClose}
                />
            </Modal>
        </SafeAreaView>
    );
};

export default ReportWork;